package deep.classloader.guess;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

public class CustomLoadOrderClassLoader extends ClassLoader {

	private String rootDir;
	private ClassLoader parent;

	public CustomLoadOrderClassLoader() {
		// super();
	}

	public CustomLoadOrderClassLoader(String rootDir) {
		// super();
		this.rootDir = rootDir;
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		// TODO Auto-generated method stub
		// return super.findClass(name);
		System.out.println("find class :" + name);
		byte[] classData = getClassData(rootDir);
		if (classData == null) {
			throw new ClassNotFoundException();
		} else {
			System.out.println("define class" + name);
			return defineClass(name, classData, 0, classData.length);
		}
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {

		if (name.startsWith("java")) {
			return loadClass(name, false);
		} else {
			synchronized (getClassLoadingLock(name)) {
				// First, check if the class has already been loaded
//				Class<?> c = findLoadedClass(name);

				Class<?> c = findClass(name);

				// this is the defining class loader; record the stats

				resolveClass(c);

				return c;
			}

		}

	}

	@Override
	protected Package definePackage(String name, String specTitle, String specVersion, String specVendor,
			String implTitle, String implVersion, String implVendor, URL sealBase) throws IllegalArgumentException {

		return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor,
				sealBase);

	}

	@Override
	protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
		System.out.println("load class :" + name);
		return super.loadClass(name, false);
	}

	private byte[] getClassData(String className) {
		// String path = classNameToPath(className);
		String path = rootDir;
		try {
			InputStream ins = new FileInputStream(path);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int bufferSize = 4096;
			byte[] buffer = new byte[bufferSize];
			int bytesNumRead = 0;
			while ((bytesNumRead = ins.read(buffer)) != -1) {
				baos.write(buffer, 0, bytesNumRead);
			}
			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private String classNameToPath(String className) {
		return rootDir + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
	}

	public String getRootDir() {
		return rootDir;
	}

	public void setRootDir(String rootDir) {
		this.rootDir = rootDir;
	}

}
